import Axios from 'axios';
let queryString = require('query-string');
import {Sign} from '../utils/Taobao';

import {taobaoParam} from '../utils/TbParams'

/**
 * 获取淘宝商品轮播图
 * @param {商品ID} productId
 */
export function getSwiper(productId) {
  return new Promise((resolve) => {
    const data = Sign(taobaoParam().app_key, taobaoParam().app_secret, 'taobao.tbk.item.info.get', {
      num_iids: productId,
    });
    const url = taobaoParam().api + `?${queryString.stringify(data)}`;
    Axios.get(url).then((res) => {
      res = res.data;
      if (res.tbk_item_info_get_response === null) {
        resolve([]);
      } else {
        var detalItem = res.tbk_item_info_get_response.results.n_tbk_item[0];
        resolve(detalItem.small_images.string);
      }
    });
  }).catch((e) => {});
}

/*
 * 獲取详情图片+商店分数
 * */
export function getDetail(productId) {
  return new Promise((resolve) => {
    Axios.all([
      Axios.get(
        `http://h5api.m.taobao.com/h5/mtop.taobao.detail.getdesc/6.0/?jsv=2.4.11&appKey=12574478&t=1538180732308&sign=e93a97b7e9a9a459297f4e689051c895&api=mtop.taobao.detail.getdesc&v=6.0&data={%22id%22%3A%22${productId}%22%2C%22type%22%3A%220%22%2C%22f%22%3A%22TB1AsvbfnqWBKNjSZFx8qwpLpla%22}`,
      ),
      Axios.get(
        `https://acs.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/?data={%22itemNumId%22%3A%22${productId}%22}`,
      ),
    ])
      .then(
        Axios.spread((desc, detail) => {
          /**
           * 处理详情图片
           */
          let descPic = [];

          for (let v of desc.data.data.wdescContent.pages) {
            let uri = v.replace(/<(.*?)>/gi, '');
            if (uri.substring(0, 2) == '//') {
              uri = `https:${uri}`;
            } else if (uri.substring(0, 4) !== 'http') {
              uri = `https://${uri}`;
            }
            if (
              uri.substring(uri.length - 3, uri.length) === 'jpg' ||
              uri.substring(uri.length - 3, uri.length) === 'png'
            ) {
              descPic.push(uri);
            }
          }

          resolve({desc: descPic, seller: detail.data.data.seller});
        }),
      )
      .catch(() => {});
  }).catch((e) => {});
}
